package user

import (
	"errors"
	"public_security/databases"
	"public_security/models"
	"public_security/plugins"
)

func Create(req *models.Users) error {
	var count int
	databases.DbDefault.Model(&models.Users{}).Select("count(id)").Where("account=?", req.Account).Scan(&count)
	if count > 0 {
		return errors.New("账号已存在")
	}
	req.Password = models.SignMD5Up(req.Password)
	if err := databases.DbDefault.Model(&models.Users{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func Update(req *models.Users) error {
	oldUser := new(models.Users)
	databases.DbDefault.Model(&models.Users{}).Where("account=?", req.Account).First(&oldUser)
	if oldUser.Id != req.Id {
		return errors.New("账号已存在")
	}
	if err := databases.DbDefault.Model(&models.Users{}).Where("id=?", req.Id).Updates(map[string]interface{}{"name": req.Name, "account": req.Account, "password": models.SignMD5Up(req.Password)}).Error; err != nil {
		return err
	}
	return nil
}

func Remove(req *models.Users) error {
	if err := databases.DbDefault.Model(&models.Users{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func Query(req *models.Users, page *plugins.ResultsPageInfo) ([]*models.Users, *plugins.ResultsPageInfo) {
	arts := make([]*models.Users, 0)
	databases.DbDefault.Model(req).Count(&page.Total).Limit(page.PerPage).Offset(page.PerPage * (page.Page - 1)).Order("create_time asc").Find(&arts)
	return arts, page
}
